
package com.insigma.business.qrcode.job._provider.impl;

import cn.hutool.core.date.DateUtil;

import com.insigma.business.qrcode.common.converter.JobCandidateResumeProviderConverter;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.job.dto.search.JobCandidateResumeBSearcher;
import com.insigma.business.qrcode.job.dto.request.JobCandidateResumeInsertRequest;
import com.insigma.business.qrcode.job.dto.request.JobCandidateResumeSearchRequest;
import com.insigma.business.qrcode.job.dto.JobResumeDetailBO;
import com.insigma.business.qrcode.intell.entity.CompanyIndustryTypeDO;
import com.insigma.business.qrcode.job.entity.JobCandidateResumeDO;
import com.insigma.business.qrcode.job.entity.JobRecruitPositionTypeDO;
import com.insigma.business.qrcode.intell.service.CompanyIndustryTypeService;
import com.insigma.business.qrcode.job._provider.JobCandidateResumeProvider;
import com.insigma.business.qrcode.job.service.JobCandidateResumeService;
import com.insigma.business.qrcode.job.service.JobRecruitPositionTypeService;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.soldier.request.BaseGetRequest;
import com.insigma.business.qrcode.job.dto.ExpectedInfoRequest;
import com.insigma.business.qrcode.job.dto.JobCandidateResumeDTO;
import com.insigma.business.qrcode.job.dto.request.JobCandidateResumeUpdateRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
@Component("jobCandidateResumeProvider")
public class JobCandidateResumeProviderImpl extends BaseProviderImpl implements JobCandidateResumeProvider {

    @Autowired
    private JobCandidateResumeService jobCandidateResumeService;

    @Autowired
    private JobRecruitPositionTypeService jobRecruitPositionTypeService;

    @Autowired
    private CompanyIndustryTypeService companyIndustryTypeService;


    @Override
    public BasePagingResponse<List<JobCandidateResumeDTO>> searchJobCandidateResume(final JobCandidateResumeSearchRequest searchRequest) {

        final BasePagingResponse<List<JobCandidateResumeDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页JobCandidateResume的请求参数不能为空");
            }

            @Override
            public void executeService() {
                if (Strings.isBlank(searchRequest.getSortKeyValueJoint())) {
                    searchRequest.setSortKeyValueJoint("createDatetime_desc");
                }

                final JobCandidateResumeBSearcher jobCandidateResumeBSearcher = JobCandidateResumeProviderConverter.convertRequestSO2Searcher(searchRequest);
                final List<JobCandidateResumeDO> jobCandidateResumeDOList = jobCandidateResumeService.search(jobCandidateResumeBSearcher);
                final List<JobCandidateResumeDTO> jobCandidateResumeDTOList = JobCandidateResumeProviderConverter.convertResponseDOList2DTOList(jobCandidateResumeDOList);
                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, jobCandidateResumeDTOList, searchRequest, jobCandidateResumeBSearcher.getTotalCount());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_CANDIDATE_RESUME_SEARCH;
            }
        });

        return basePagingResponse;
    }

    @Override
    public BasePagingResponse<List<JobCandidateResumeDTO>> searchResumeOfCompanyAndPosition(JobCandidateResumeSearchRequest request) {

        BizCheckUtil.checkNotNull(request);

        final JobCandidateResumeBSearcher searcher = JobCandidateResumeProviderConverter.convertRequestSO2Searcher(request);
        final List<JobResumeDetailBO> jobCandidateResumeDOList = jobCandidateResumeService.searchResumeOfPosition(searcher);
        final List<JobCandidateResumeDTO> jobCandidateResumeDTOList = JobCandidateResumeProviderConverter.convertResponseBOList2DTOList(jobCandidateResumeDOList);

        return ResponseUtils.buildSuccessPagingResponse(jobCandidateResumeDTOList, searcher);
    }


    @Override
    public BaseResponse<JobCandidateResumeDTO> getJobCandidateResume(final BaseGetRequest baseGetRequest) {

        final BaseResponse<JobCandidateResumeDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条JobCandidateResume的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final JobCandidateResumeDO jobCandidateResumeDO = jobCandidateResumeService.get((String) baseGetRequest.getId());
                final JobCandidateResumeDTO remoteObj = JobCandidateResumeProviderConverter.convertResponseDO2DTO(jobCandidateResumeDO);
                if (remoteObj != null) {
                    remoteObj.build();
                }

                if (remoteObj != null) {
                    Date birthday = remoteObj.getBirthday();
                    if (birthday != null) {
                        remoteObj.setAge(DateUtil.ageOfNow(birthday));
                    }
                }

                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_CANDIDATE_RESUME_GET;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<JobCandidateResumeDTO> getMyResume(String userId) {

        BizCheckUtil.checkNotBlank(userId, "userId不能为空");

        JobCandidateResumeDO jobCandidateResumeDO = jobCandidateResumeService.getByCandidateId(userId);
        final JobCandidateResumeDTO remoteObj = JobCandidateResumeProviderConverter.convertResponseDO2DTO(jobCandidateResumeDO);
        if (remoteObj != null) {
            remoteObj.build();
        }
        return ResponseUtils.buildSuccessResponse(remoteObj);
    }


    @Override
    public BaseResponse<String> insertJobCandidateResume(final JobCandidateResumeInsertRequest insertRequest) {

        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增JobCandidateResume的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final JobCandidateResumeDO jobCandidateResumeDO = JobCandidateResumeProviderConverter.convertRequestIO2DO(insertRequest);
                jobCandidateResumeService.insert(jobCandidateResumeDO);
                ResponseUtils.setupSuccessResponse(baseResponse, jobCandidateResumeDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_CANDIDATE_RESUME_INSERT;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> updateJobCandidateResume(final JobCandidateResumeUpdateRequest updateRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改JobCandidateResume的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierId(), "操作人不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");
            }

            @Override
            public void executeService() {
                JobCandidateResumeDO jobCandidateResumeDO = JobCandidateResumeProviderConverter.convertRequestUO2DO(updateRequest);
                Integer affectRowNum = jobCandidateResumeService.update(jobCandidateResumeDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_CANDIDATE_RESUME_UPDATE;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> deleteJobCandidateResume(final BaseDeleteRequest deleteRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除JobCandidateResume的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(), "操作人类型不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getModifierId(), "操作人不能为空");
            }

            @Override
            public void executeService() {
                final Integer affectRowNum = jobCandidateResumeService.delete((String) deleteRequest.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.JOB_CANDIDATE_RESUME_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> updateMyResume(JobCandidateResumeUpdateRequest request) {

        BizCheckUtil.checkNotNull(request.getCandidateId(), "candidate id 不能为null");

        JobCandidateResumeDO resumeDO = jobCandidateResumeService.getByCandidateId(request.getCandidateId());
        request.build();
        if (resumeDO == null) {
            resumeDO = new JobCandidateResumeDO();
            BeanUtils.copyProperties(request, resumeDO);
            Integer insert = jobCandidateResumeService.insert(resumeDO);
            return ResponseUtils.buildSuccessResponse(insert);
        } else {
            BeanUtils.copyProperties(request, resumeDO);
            Integer affectRowNum = jobCandidateResumeService.update(resumeDO);
            return ResponseUtils.buildSuccessResponse(affectRowNum);
        }
    }

    @Override
    public BaseResponse<Integer> updateMyResumeOfExpect(JobCandidateResumeUpdateRequest request) {

        BizCheckUtil.checkNotNull(request.getCandidateId(), "candidate id 不能为null");
        JobCandidateResumeDO resumeDO = jobCandidateResumeService.getByCandidateId(request.getCandidateId());

        if (resumeDO != null && Strings.isNotBlank(resumeDO.getExpectedInfo())) {
            return ResponseUtils.buildSuccessResponse(0);
        }

        List<ExpectedInfoRequest> expectedDetail = request.getExpectedDetail();
        if (!CollectionUtils.isEmpty(expectedDetail)) {
            for (ExpectedInfoRequest item : expectedDetail) {
                if (Strings.isNotBlank(item.getExpectedIndustryId()) && Strings.isBlank(item.getExpectedIndustryName())) {
                    CompanyIndustryTypeDO companyIndustryTypeDO = companyIndustryTypeService.get(item.getExpectedIndustryId());
                    if (companyIndustryTypeDO != null) {
                        item.setExpectedIndustryName(companyIndustryTypeDO.getName());
                    }
                }

                if (Strings.isNotBlank(item.getExpectedPositionTypeId()) && Strings.isBlank(item.getExpectedPositionTypeName())) {
                    JobRecruitPositionTypeDO byCode = jobRecruitPositionTypeService.getByCode(item.getExpectedPositionTypeId());
                    if (byCode != null) {
                        item.setExpectedPositionTypeName(byCode.getName());
                    }
                }


                String expectedSalary = item.getExpectedSalary();
                try {
                    if (Strings.isNotBlank(expectedSalary)) {
                        expectedSalary = expectedSalary.replace("[", "");
                        expectedSalary = expectedSalary.replace("]", "");
                        String[] split = expectedSalary.split(",");
                        if (split.length >= 2) {
                            String s1 = split[0];
                            String s2 = split[1];
                            Integer i1 = Integer.valueOf(s1);
                            Integer i2 = Integer.valueOf(s2);
                            Integer si1 = i1 / 1000;
                            Integer si2 = (i2 - i1) / 1000 - 1;
                            expectedSalary = "[" + si1 + "," + si2 + "]";
                            item.setExpectedSalary(expectedSalary);
                        }
                    }
                } catch (Exception e) {
                    log.error("e:{}", e);
                    item.setExpectedSalary("");
                }
            }
        }

        request.build();
        if (resumeDO == null) {
            resumeDO = new JobCandidateResumeDO();
            BeanUtils.copyProperties(request, resumeDO);
            Integer insert = jobCandidateResumeService.insert(resumeDO);
            return ResponseUtils.buildSuccessResponse(insert);
        } else {
            resumeDO.setExpectedInfo(request.getExpectedInfo());
            resumeDO.setExpectedSalary(request.getExpectedSalary());
            resumeDO.setExpectedCity(request.getExpectedCity());
            resumeDO.setExpectedPositionTypeId(request.getExpectedPositionTypeId());
            resumeDO.setExpectedPositionTypeName(request.getExpectedPositionTypeName());
            resumeDO.setExpectedIndustryId(request.getExpectedIndustryId());
            resumeDO.setExpectedIndustryName(request.getExpectedIndustryName());

            Integer affectRowNum = jobCandidateResumeService.update(resumeDO);
            return ResponseUtils.buildSuccessResponse(affectRowNum);
        }
    }

    public static void main(String[] args) {
        String expectedSalary = "[8000,10000]";
        expectedSalary = expectedSalary.replace("[", "");
        expectedSalary = expectedSalary.replace("]", "");
        String[] split = expectedSalary.split(",");
        if (split.length >= 2) {
            String s1 = split[0];
            String s2 = split[1];
            Integer i1 = Integer.valueOf(s1);
            Integer i2 = Integer.valueOf(s2);
            Integer si1 = i1 / 1000;
            Integer si2 = (i2 - i1) / 1000 - 1;
            expectedSalary = "[" + si1 + "," + si2 + "]";
            System.out.println(expectedSalary);
        }
    }

}
